package com.ruoyi.api.kehu;

import com.github.pagehelper.PageHelper;
import com.ruoyi.system.mapper.JiajiaProxyApplicationMapper;
import com.ruoyi.system.utils.TokenUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.domain.JiajiaUser;
import com.ruoyi.system.domain.JiajiaUserLike;
import com.ruoyi.system.domain.JiajiaWorker;
import com.ruoyi.system.service.IJiajiaChongzhiRecordService;
import com.ruoyi.system.service.IJiajiaOrderService;
import com.ruoyi.system.service.IJiajiaUserMoneyChangeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api/kehu/other")
@Api(tags = "个人主页功能")
public class ApiUserOtherController {

    @Autowired
    private IJiajiaUserLikeService userLikeService;

    @Autowired
    private IJiajiaWorkerService workerService;

    @Autowired
    private IJiajiaUserService userService;

    @Autowired
    private IJiajiaChongzhiService chongzhiService;

    @Autowired
    private IJiajiaFankuiService fankuiService;

    @Autowired
    private IJiajiaUserCouponService userCouponService;

    @Autowired
    private IJiajiaWorkerService jiajiaWorkerService;

    @Autowired
    private IJiajiaJuBaoService jiajiaJuBaoService;

    @Autowired
    private IJiajiaMessageService jiajiaMessageService;

    @Autowired
    private IJiajiaChongzhiService jiajiaChongzhiService;

    @Autowired
    private IJiajiaChongzhiRecordService jiajiaChongzhiRecordService;

    @Autowired
    private IJiajiaOrderService orderService;

    @Autowired
    private IJiajiaUserMoneyChangeService moneyChangeService;

    @Resource
    private JiajiaProxyApplicationMapper jiajiaProxyApplicationMapper;

    @ApiOperation("我的关注")
    @PostMapping("/like")
    public AjaxResult like() {
        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null) return AjaxResult.error("没有查询到用户信息");

        JiajiaUserLike userLike = new JiajiaUserLike();
        userLike.setUid(user.getId());
        List<JiajiaUserLike> userLikeList = userLikeService.selectJiajiaUserLikeList(userLike);

        String wids = StringUtils.listsToSbStr(userLikeList, "wid");

        JiajiaWorker worker = new JiajiaWorker();
        worker.getParams().put("idsArr", wids.split(","));
        List<JiajiaWorker> workerList = workerService.selectWorkerList(worker);

        //计算距离
        for (JiajiaWorker model : workerList) {
            model.getParams().put("juLi",TokenUtil.getLuLi(model.getLat(),model.getLng()));
        }

        return AjaxResult.success(workerList);
    }


    @ApiOperation("我的钱包")
    @PostMapping("/qianBao")
    public AjaxResult qianBao() {

        JSONObject resObj = new JSONObject();

        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null) return AjaxResult.error("没有查询到用户信息");
        resObj.put("yue", user.getMoney());

        JiajiaChongzhi chongzhi = new JiajiaChongzhi();
        chongzhi.setDel(0);
        List<JiajiaChongzhi> chongzhiList = chongzhiService.selectJiajiaChongzhiList(chongzhi);

        resObj.put("list", chongzhiList);

        return AjaxResult.success(resObj);
    }

    @ApiOperation("意见反馈")
    @PostMapping("/fanKui")
    public AjaxResult yiJianFanKui(@RequestBody JiajiaFankui fankui) {
        fankui.setUid(TokenUtil.getUid());
        fankuiService.insertJiajiaFankui(fankui);
        return AjaxResult.success("反馈成功");
    }

    @ApiOperation("优惠券")
    @PostMapping("/couponList")
    public AjaxResult couponList(@ApiParam(value = "(0全部 1已使用 2已过期)") @RequestParam Integer status) {

        JiajiaUserCoupon userCoupon = new JiajiaUserCoupon();
        userCoupon.setUid(TokenUtil.getUid());
        if (status < 2) {
            userCoupon.setStatus(status);
        } else {
            userCoupon.getParams().put("yiGuoQi", "true");
        }
        List<JiajiaUserCoupon> userCouponList = userCouponService.selectJiajiaUserCouponList(userCoupon);

        for (JiajiaUserCoupon model : userCouponList) {
            model.getParams().put("isGuoQi", "0");
            if (model.getSxTime().before(new Date())) {
                model.getParams().put("isGuoQi", "1");
            }
        }

        Collections.sort(userCouponList, new Comparator<JiajiaUserCoupon>() {
            @Override
            public int compare(JiajiaUserCoupon o1, JiajiaUserCoupon o2) {
                return Integer.valueOf(o1.getParams().get("isGuoQi").toString()) - Integer.valueOf(o2.getParams().get("isGuoQi").toString());
            }
        });


        return AjaxResult.success(userCouponList);
    }

    @ApiOperation("举报提交")
    @PostMapping("/juBao")
    public AjaxResult juBao(@RequestParam @ApiParam(value = "社工id") Long wid,
                            @RequestParam @ApiParam(value = "举报原因") String notes,
                            @RequestParam @ApiParam(value = "举报内容") String contents,
                            @RequestParam(required = false) @ApiParam(value = "举报图片路径") String url
    ) {

        if (StringUtils.isEmpty(notes)){
            return AjaxResult.error("请选择举报原因");
        }
        if (StringUtils.isEmpty(notes)){
            return AjaxResult.error("请选择填写举报内容");
        }

        JiajiaJuBao juBao = new JiajiaJuBao();
        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        JiajiaWorker worker = jiajiaWorkerService.selectJiajiaWorkerById(wid);
        juBao.setWid(wid);
        juBao.setJiShiName(worker.getName());
        juBao.setNotes(notes);
        juBao.setContent(contents);
        juBao.setUrl(url);
        juBao.setUid(TokenUtil.getUid());
        juBao.setUserName(user.getName());

        jiajiaJuBaoService.insertJiajiaJuBao(juBao);

        return AjaxResult.success("举报成功");
    }

    @ApiOperation("用户系统消息")
    @PostMapping("/sysMessage")
    public AjaxResult sysmessage(@RequestParam Integer pageNum) {

        JiajiaMessage message = new JiajiaMessage();
        message.setUid(TokenUtil.getUid());
        message.setType(2);
        PageHelper.startPage(pageNum,20,"addtime desc");
        List<JiajiaMessage> messages = jiajiaMessageService.selectJiajiaMessageList(message);

        jiajiaMessageService.yiDuAllMessage(message);

        return AjaxResult.success(messages);
    }

    @ApiOperation("充值系统")
    @PostMapping("/chongZhi")
    @Transactional
    public AjaxResult chongZhi(@RequestParam @ApiParam(value = "充值档次id") Long id,
                               @RequestParam @ApiParam(value = "充值金额") Integer money) {

        JiajiaChongzhi chongZhi = jiajiaChongzhiService.selectJiajiaChongzhiById(id);
        if (chongZhi == null) {
            chongZhi = new JiajiaChongzhi();
            chongZhi.setChongZhiMoney(new BigDecimal(money));
            chongZhi.setZengSongMoney(BigDecimal.ZERO);
        }
        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null) return AjaxResult.refreshAgain();

        JiajiaChongzhiRecord record = new JiajiaChongzhiRecord();

        //保存充值记录
        Random random = new Random();
        String chongZhiSn = System.currentTimeMillis()/1000+""+(random.nextInt(8999)+1000);

        record.setChongZhiSn(chongZhiSn);
        record.setUid(TokenUtil.getUid());
        record.setChongZhi(chongZhi.getChongZhiMoney());
        record.setZengSong(chongZhi.getZengSongMoney());
        jiajiaChongzhiRecordService.insertJiajiaChongzhiRecord(record);

        return AjaxResult.success("充值成功",chongZhiSn);
    }

    @ApiOperation(value = "关注社工")
    @PostMapping("likeWorker")
    public AjaxResult likeWorker(@RequestParam Long wid){

        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null)return AjaxResult.notLogin();

        JiajiaUserLike userLike = new JiajiaUserLike();
        userLike.setUid(user.getId());
        userLike.setWid(wid);
        List<JiajiaUserLike> userLikeList = userLikeService.selectJiajiaUserLikeList(userLike);
        if (userLikeList.isEmpty()){
            userLikeService.insertJiajiaUserLike(userLike);
        }else {
            userLikeService.deleteJiajiaUserLikeByIds(userLikeList.get(0).getId().toString());
        }

        return AjaxResult.success();
    }

    @ApiOperation("查看账单")
    @PostMapping("/moneyChangeList")
    public AjaxResult moneyChangeList(@RequestParam Integer pageNo,
                                      @RequestParam Integer pageSize) {

        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        if (user == null)return AjaxResult.notLogin();

        JiajiaUserMoneyChange jiajiaUserMoneyChange = new JiajiaUserMoneyChange();
        jiajiaUserMoneyChange.setUid(user.getId());

        PageHelper.startPage(pageNo,pageSize,"addtime desc");
        List<JiajiaUserMoneyChange> changeList = moneyChangeService.selectJiajiaUserMoneyChangeList(jiajiaUserMoneyChange);

        return AjaxResult.success(changeList);
    }


    @ApiOperation("我的推荐官")
    @PostMapping("/myReference")
    public AjaxResult myReference() {
        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        System.out.println("我的推荐官电话"+user.getInviter()+"-----------------------------------------------------------");
        //String reference = user.getReference();
        String inviter = user.getInviter();
        JiajiaUser jiajiaUser = userService.selectjiajiaUser(inviter);
        System.out.println("我的推荐官信息"+jiajiaUser+"------------------------------------------------------------------");
        return AjaxResult.success(jiajiaUser);
    }

    @ApiOperation("我的团队")
    @GetMapping("/myTeam")
    public AjaxResult myTeam(Integer type) {
        Map<String,Object> map=new HashMap<>();
        JiajiaUser user = userService.selectJiajiaUserById(TokenUtil.getUid());
        Long  numberOfPeopleInTheGroup= userService.select(user.getPhone(),type);
        String reference = user.getPhone();
        List<JiajiaUser> jiajiaUsers = userService.selectMyTeam(reference,type);
        AtomicInteger peopleNum= new AtomicInteger(1);
        jiajiaUsers.stream().forEach(a->{
            String phone = a.getPhone();
            List<JiajiaUser> jiajiaUsers1 = userService.selectMyTeam(phone,type);
            if(Optional.ofNullable(jiajiaUsers1).isPresent()){
                peopleNum.addAndGet(jiajiaUsers1.size());
            }
            Long integral =userService.select(a.getPhone(),type);
            a.setNumberOfPeopleInTheGroup(integral);
            List<JiajiaProxyApplication> proxyApplications = jiajiaProxyApplicationMapper.selectByUserId(user.getId());
            List<Integer> list= proxyApplications.stream().map(JiajiaProxyApplication::getType).collect(Collectors.toList());
            a.getParams().put("type",list);
        });
        map.put("numberOfPeopleInTheGroup",numberOfPeopleInTheGroup);
        map.put("myTeam",jiajiaUsers);
        map.put("peopleNum",peopleNum);
        return AjaxResult.success(map);
    }

}

